package tk.mybatis.springboot.api.controller;

import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tk.mybatis.springboot.model.AccessConnect;
import tk.mybatis.springboot.model.AccessPurview;
import tk.mybatis.springboot.model.AccessRole;
import tk.mybatis.springboot.model.AccessVisit;
import tk.mybatis.springboot.model.Commodity;
import tk.mybatis.springboot.model.Message;
import tk.mybatis.springboot.model.TUser;
import tk.mybatis.springboot.model.Usermessage;
import tk.mybatis.springboot.service.AdminService;
import tk.mybatis.springboot.share.util.RedisUtils;
import tk.mybatis.springboot.share.util.UniqId;

/**
 * @author liujh
 */
@Controller
@RequestMapping(value = "admin")
public class AdminController extends BaseController{
	@Autowired
	private AdminService adminService;	
    @RequestMapping(value = "login")
    @ResponseBody
    public Message login(HttpServletRequest request, HttpServletResponse response, String phone, String pwd)throws Exception {
    	String sessionId=request.getSession().getId();
    	return adminService.login(sessionId, phone, pwd);
    }
    
    @RequestMapping(value = "logout")
    @ResponseBody
    public Message logout(HttpServletRequest request, HttpServletResponse response, String phone, String pwd)throws Exception {
    	String sessionId=request.getSession().getId();
    	RedisUtils.delObj(sessionId);
    	return Message.success();
    }
    
    @RequestMapping(value = "clerk/find")
    @ResponseBody
    public Message clerkFind(HttpServletRequest request, HttpServletResponse response, TUser tUser, Integer pageNumber, Integer pageSize)throws Exception {
    	return adminService.clerkFind(tUser, pageNumber, pageSize);
    }
    
    @RequestMapping(value = "clerk/add")
    @ResponseBody
    public Message clerkAdd(HttpServletRequest request, HttpServletResponse response, TUser tUser)throws Exception {
    	return adminService.clerkAdd(tUser);
    }
    
    @RequestMapping(value = "clerk/edit")
    @ResponseBody
    public Message clerkEdit(HttpServletRequest request, HttpServletResponse response, TUser tUser)throws Exception {
    	return adminService.clerkEdit(tUser);
    }
    
    @RequestMapping(value = "clerk/status")
    @ResponseBody
    public Message clerkStatus(HttpServletRequest request, HttpServletResponse response, String id, String status)throws Exception {
    	return adminService.clerkStatus(id, status);
    }
    
    @RequestMapping(value = "clerk/del")
    @ResponseBody
    public Message clerkDel(HttpServletRequest request, HttpServletResponse response, String id)throws Exception {
    	return adminService.clerkDel(id);
    }
    
    @RequestMapping(value = "charmtype/find")
    @ResponseBody
    public Message charmtypeFind(HttpServletRequest request, HttpServletResponse response)throws Exception {
    	return adminService.charmtypeFind();
    }
    
    @RequestMapping(value = "charmtype/add")
    @ResponseBody
    public Message charmtypeAdd(HttpServletRequest request, HttpServletResponse response, String name)throws Exception {
    	return adminService.charmtypeAdd(name);
    }
    
    @RequestMapping(value = "charmtype/edit")
    @ResponseBody
    public Message charmtypeEdit(HttpServletRequest request, HttpServletResponse response, String id, String name)throws Exception {
    	return adminService.charmtypeEdit(id, name);
    }
    
    @RequestMapping(value = "charmtype/del")
    @ResponseBody
    public Message charmtypeDel(HttpServletRequest request, HttpServletResponse response, String id)throws Exception {
    	return adminService.charmtypeDel(id);
    }
    
    @RequestMapping(value = "goods/find")
    @ResponseBody
    public Message goodsFind(HttpServletRequest request, HttpServletResponse response, Commodity commodity, Integer pageNumber, Integer pageSize)throws Exception {
    	return adminService.goodsFind(commodity, pageNumber, pageSize);
    }
    
    @RequestMapping(value = "goods/add")
    @ResponseBody
    public Message goodsAdd(HttpServletRequest request, HttpServletResponse response, String name, String price)throws Exception {
    	return adminService.goodsAdd(name, price);
    }
    
    @RequestMapping(value = "goods/edit")
    @ResponseBody
    public Message goodsEdit(HttpServletRequest request, HttpServletResponse response, Commodity commodity)throws Exception {
    	return adminService.goodsEdit(commodity);
    }
    
    @RequestMapping(value = "goods/del")
    @ResponseBody
    public Message goodsDel(HttpServletRequest request, HttpServletResponse response, String id)throws Exception {
    	return adminService.goodsDel(id);
    }
    
    @RequestMapping(value = "goods/status")
    @ResponseBody
    public Message goodsStatus(HttpServletRequest request, HttpServletResponse response, String id, Integer status)throws Exception {
    	return adminService.goodsStatus(id, status);
    }
    
    @RequestMapping(value = "user/find")
    @ResponseBody
    public Message userFind(HttpServletRequest request, HttpServletResponse response, TUser tUser, Integer pageNumber, Integer pageSize)throws Exception {
    	return adminService.userFind(tUser, pageNumber, pageSize);
    }
    
    @RequestMapping(value = "user/status")
    @ResponseBody
    public Message userStatus(HttpServletRequest request, HttpServletResponse response, String id, String status)throws Exception {
    	return adminService.userStatus(id, status);
    }
    
    @RequestMapping(value = "user/del")
    @ResponseBody
    public Message userDel(HttpServletRequest request, HttpServletResponse response, String id)throws Exception {
    	return adminService.clerkDel(id);
    }
    
    @RequestMapping(value = "user/edit")
    @ResponseBody
    public Message userEdit(HttpServletRequest request, HttpServletResponse response, TUser tUser)throws Exception {
    	return adminService.clerkEdit(tUser);
    }
    
    @RequestMapping(value = "user/access")
    @ResponseBody
    public Message userAccess(HttpServletRequest request, HttpServletResponse response, String userId, String accessId)throws Exception {
    	return adminService.userAccess(userId, accessId);
    }
    
    @RequestMapping(value = "comment/find")
    @ResponseBody
    public Message commentFind(HttpServletRequest request, HttpServletResponse response, String userName, String context, Date contextDateBegin,
    		Date contextDateEnd, Integer pageNumber, Integer pageSize, Integer status)throws Exception {
    	return adminService.commentFind(userName, context, contextDateBegin, contextDateEnd, pageNumber, pageSize, status);
    }
    
    @RequestMapping(value = "comment/reply")
    @ResponseBody
    public Message commentReply(HttpServletRequest request, HttpServletResponse response, String id, String reply)throws Exception {
    	return adminService.commentReply(id, reply);
    }
    
    @RequestMapping(value = "comment/status")
    @ResponseBody
    public Message commentStatus(HttpServletRequest request, HttpServletResponse response, String id, Integer status)throws Exception {
    	return adminService.commentStatus(id, status);
    }
    
    @RequestMapping(value = "comment/del")
    @ResponseBody
    public Message commentDel(HttpServletRequest request, HttpServletResponse response, String id)throws Exception {
    	return adminService.commentDel(id);
    }
    
    @RequestMapping(value = "manager/pwd")
    @ResponseBody
    public Message managerPwd(HttpServletRequest request, HttpServletResponse response, String id, String pwdNew, String pwdOld)throws Exception {
    	return adminService.managerPwd(id, pwdNew, pwdOld);
    }
    
    @RequestMapping(value = "manager/edit")
    @ResponseBody
    public Message managerEdit(HttpServletRequest request, HttpServletResponse response, TUser tUser)throws Exception {
    	return adminService.clerkEdit(tUser);
    }
    
    @RequestMapping(value = "manager/add")
    @ResponseBody
    public Message managerAdd(HttpServletRequest request, HttpServletResponse response, TUser tUser)throws Exception {
    	return adminService.managerAdd(tUser);
    }
    
    @RequestMapping(value = "order/find")
    @ResponseBody
    public Message orderFind(HttpServletRequest request, HttpServletResponse response, String orderNo, String phone, Date createDateBegin,
    		Date createDateEnd, Integer pageNumber, Integer pageSize, String address)throws Exception {
    	return adminService.orderFind(orderNo, phone, createDateBegin, createDateEnd, pageNumber, pageSize, address);
    }
    
    @RequestMapping(value = "order/status")
    @ResponseBody
    public Message orderStatus(HttpServletRequest request, HttpServletResponse response, String id, Integer status)throws Exception {
    	return adminService.orderStatus(id, status);
    }
    
    @RequestMapping(value = "order/history")
    @ResponseBody
    public Message orderHistory(HttpServletRequest request, HttpServletResponse response, String id)throws Exception {
    	return adminService.orderHistory(id);
    }
    
    @RequestMapping(value = "notification/find")
    @ResponseBody
    public Message notificationFind(HttpServletRequest request, HttpServletResponse response, Usermessage userMessage, Integer pageNumber, Integer pageSize)throws Exception {
    	return adminService.notificationFind(userMessage, pageNumber, pageSize);
    }
    
    @RequestMapping(value = "notification/add")
    @ResponseBody
    public Message notificationAdd(HttpServletRequest request, HttpServletResponse response, Usermessage userMessage)throws Exception {
    	return adminService.notificationAdd(userMessage);
    }
    
    @RequestMapping(value = "notification/edit")
    @ResponseBody
    public Message notificationEdit(HttpServletRequest request, HttpServletResponse response, Usermessage userMessage)throws Exception {
    	return adminService.notificationEdit(userMessage);
    }
    
    @RequestMapping(value = "notification/del")
    @ResponseBody
    public Message notificationDel(HttpServletRequest request, HttpServletResponse response, String id)throws Exception {
    	return adminService.notificationDel(id);
    }
    
    @RequestMapping(value = "access/rolefind")
    @ResponseBody
    public Message accessRolefind(HttpServletRequest request, HttpServletResponse response, String title, String abbreviation, Integer pageNumber, Integer pageSize)throws Exception {
    	return adminService.accessRolefind(title, abbreviation, pageNumber, pageSize);
    }
    
    @RequestMapping(value = "access/roleadd")
    @ResponseBody
    public Message accessRoleadd(HttpServletRequest request, HttpServletResponse response, String title, String abbreviation)throws Exception {
    	return adminService.accessRoleadd(title, abbreviation);
    }
    
    @RequestMapping(value = "access/roledel")
    @ResponseBody
    public Message accessRoledel(HttpServletRequest request, HttpServletResponse response, String id)throws Exception {
    	return adminService.accessRoledel(id);
    }
    
    @RequestMapping(value = "access/rolestatus")
    @ResponseBody
    public Message accessRolestatus(HttpServletRequest request, HttpServletResponse response, String id, String status)throws Exception {
    	return adminService.accessRolestatus(id, status);
    }
    
    @RequestMapping(value = "access/roleedit")
    @ResponseBody
    public Message accessRoleedit(HttpServletRequest request, HttpServletResponse response, AccessRole accessRole)throws Exception {
    	return adminService.accessRoleedit(accessRole);
    }
    
    @RequestMapping(value = "access/addrole")
    @ResponseBody
    public Message accessAddrole(HttpServletRequest request, HttpServletResponse response, String role_id, String purview_id)throws Exception {
    	List<AccessConnect> accessConnects = Lists.newArrayList();
    	String[] split = purview_id.split(",");
    	for (String string : split) {
    		AccessConnect accessConnect = new AccessConnect();
    		accessConnect.setId(UniqId.getUid());
    		accessConnect.setRole_id(role_id);
    		accessConnect.setPurview_id(string);
    		accessConnects.add(accessConnect);
		}
    	return adminService.accessAddrole(accessConnects);
    }
    
    @RequestMapping(value = "access/addvisit")
    @ResponseBody
    public Message accessAddvisit(HttpServletRequest request, HttpServletResponse response, String role_id, String visit_id)throws Exception {
    	List<AccessConnect> accessConnects = Lists.newArrayList();
    	String[] split = visit_id.split(",");
    	for (String string : split) {
    		AccessConnect accessConnect = new AccessConnect();
    		accessConnect.setId(UniqId.getUid());
    		accessConnect.setRole_id(role_id);
    		accessConnect.setVisit_id(string);
    		accessConnects.add(accessConnect);
		}
    	return adminService.accessAddrole(accessConnects);
    }
    
    @RequestMapping(value = "access/purviewfind")
    @ResponseBody
    public Message accessPurviewfind(HttpServletRequest request, HttpServletResponse response, AccessPurview accessPurview, Integer pageNumber, Integer pageSize)throws Exception {
    	return adminService.accessPurviewfind(accessPurview, pageNumber, pageSize);
    }
    
    @RequestMapping(value = "access/purviewadd")
    @ResponseBody
    public Message accessPurviewadd(HttpServletRequest request, HttpServletResponse response, AccessPurview accessPurview)throws Exception {
    	return adminService.accessPurviewadd(accessPurview);
    }
    
    @RequestMapping(value = "access/purviewdel")
    @ResponseBody
    public Message accessPurviewdel(HttpServletRequest request, HttpServletResponse response, String id)throws Exception {
    	return adminService.accessPurviewdel(id);
    }
    
    @RequestMapping(value = "access/purviewedit")
    @ResponseBody
    public Message accessPurviewedit(HttpServletRequest request, HttpServletResponse response, AccessPurview accessPurview)throws Exception {
    	return adminService.accessPurviewedit(accessPurview);
    }
    
    @RequestMapping(value = "access/purviewstatus")
    @ResponseBody
    public Message accessPurviewstatus(HttpServletRequest request, HttpServletResponse response, AccessPurview accessPurview)throws Exception {
    	return adminService.accessPurviewedit(accessPurview);
    }
    
    @RequestMapping(value = "access/visittree")
    @ResponseBody
    public Message accessVisittree(HttpServletRequest request, HttpServletResponse response)throws Exception {
    	return adminService.accessVisittree();
    }
    
    @RequestMapping(value = "access/visitadd")
    @ResponseBody
    public Message accessVisitadd(HttpServletRequest request, HttpServletResponse response, AccessVisit accessVisit)throws Exception {
    	return adminService.accessVisitadd(accessVisit);
    }
    
    @RequestMapping(value = "access/visitdel")
    @ResponseBody
    public Message accessVisitdel(HttpServletRequest request, HttpServletResponse response, String id)throws Exception {
    	return adminService.accessVisitdel(id);
    }
    
    @RequestMapping(value = "access/visitstatus")
    @ResponseBody
    public Message accessVisitstatus(HttpServletRequest request, HttpServletResponse response, String id, String status)throws Exception {
    	return adminService.accessVisitstatus(id, status);
    }
    
    @RequestMapping(value = "access/visitedit")
    @ResponseBody
    public Message accessVisitedit(HttpServletRequest request, HttpServletResponse response, AccessVisit accessVisit)throws Exception {
    	return adminService.accessVisitedit(accessVisit);
    }
    
    @RequestMapping(value = "imgupload")
    @ResponseBody
    public Message imgupload(HttpServletRequest request, HttpServletResponse response)throws Exception {                          
    String imgName = "";
        if (ServletFileUpload.isMultipartContent(request)) {  
	        try {  
	            	// 1. 创建DiskFileItemFactory对象，设置缓冲区大小和临时文件目录  
	            DiskFileItemFactory factory = new DiskFileItemFactory();  
	            // System.out.println(System.getProperty("java.io.tmpdir"));//默认临时文件夹  
	      
	            // 2. 创建ServletFileUpload对象，并设置上传文件的大小限制。  
	            ServletFileUpload sfu = new ServletFileUpload(factory);  
	            sfu.setSizeMax(10 * 1024 * 1024);// 以byte为单位 不能超过10M 1024byte =  
	                             // 1kb 1024kb=1M 1024M = 1G  
	            sfu.setHeaderEncoding("utf-8");  
	      
	            // 3.  
	            // 调用ServletFileUpload.parseRequest方法解析request对象，得到一个保存了所有上传内容的List对象。  
	            @SuppressWarnings("unchecked")
	            List<FileItem> fileItemList = sfu.parseRequest(request);  
	            Iterator<FileItem> fileItems = fileItemList.iterator();  
	            String filePath = request.getSession().getServletContext().getRealPath("img/");
	            // 4. 遍历list，每迭代一个FileItem对象，调用其isFormField方法判断是否是上传文件 
	            
	            while (fileItems.hasNext()) {  
	                FileItem fileItem = fileItems.next();  
	                // 普通表单元素  
	                if (fileItem.isFormField()) {  
	                String name = fileItem.getFieldName();// name属性值  
	                String value = fileItem.getString("utf-8");// name对应的value值  
	      
	                System.out.println(name + " = " + value);  
	                }  
	                // <input type="file">的上传文件的元素  
	                else {  
	                String fileName = fileItem.getName();// 文件名称  
	                System.out.println("原文件名：" + fileName);// Koala.jpg  
	      
	                String suffix = fileName.substring(fileName.lastIndexOf('.'));  
	                System.out.println("扩展名：" + suffix);// .jpg  
	      
	                // 新文件名（唯一）  
	                String newFileName = new Date().getTime() + suffix;  
	                System.out.println("新文件名：" + newFileName);// image\1478509873038.jpg  
	      
	                // 5. 调用FileItem的write()方法，写入文件  
	                File file = new File(filePath+newFileName);  
	                System.out.println(file.getAbsolutePath());  
	                fileItem.write(file);  
	      
	                // 6. 调用FileItem的delete()方法，删除临时文件  
	                fileItem.delete();
	                imgName += newFileName;
	      
	                }  
	            }  
            } catch (FileUploadException e) {  
            	e.printStackTrace();  
            } catch (Exception e) {  
            	e.printStackTrace();  
            } 
            return Message.success("上传成功", imgName);
        } 
        return Message.error();
    }
}
